<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="title" :custom-back="goBack" style="z-index: 99999"></theme-navbar>
    <!-- #endif -->
    <u-toast ref="uToast" />
    <u-form :model="schoolForm" :rules="rules" :errorType="errorType" style="padding: 0px 15px;" ref="uForm">
      <u-form-item label="区域名称" :label-width="130" prop="prohibitName" required>
        <u-input input-align="right" placeholder="请输入区域名称" :custom-style="valueStyle" v-model="schoolForm.prohibitName" />
      </u-form-item>
      <u-form-item label="区域类型" :label-width="130" prop="prohibitClassifyName" required>
        <u-input input-align="right" :disabled="true" v-model="schoolForm.prohibitClassifyName" type="select" placeholder="请选择" @click="prohibitClassifyClick"/>
        <u-select v-model="prohibitClassifyShow" mode="single-column" :list="prohibitClassifyList" @confirm="prohibitClassifyConfirm"></u-select>
        <!-- <z-dict-select dictType="T_COMPLAINT_TYPE" v-model="formData.complaintTypeText" @confirm="complaintTypeConfirm"></z-dict-select> -->
      </u-form-item>
      <u-form-item label="地址" :label-width="130" prop="prohibitAddr" required>
        <u-input input-align="right" v-model="schoolForm.prohibitAddr" placeholder="请输入地址" :custom-style="valueStyle" />
        <u-icon
          name="map-fill" :color="$theme.u_type_primary" size="50"
          @click="getLocation('addr')"
        ></u-icon>
      </u-form-item>
    </u-form>
    <view v-if="handlerType == 'edit'">
    <view class="divider-info">
      位置信息<u-tag class="client-num" type="primary" :text="coordinatesList.length" shape="circle" />
      <span class="sub-info">(向左滑动删除)</span>
      <u-icon style="float:right;" :color="$theme.u_type_primary" name="plus" size="38" @click="handlerDoMore()"></u-icon>
    </view>
    <view class="card" v-for="(item, index) in coordinatesList" :key="index">
      <u-swipe-action
        :index="index"
        :show="item.show"
        :options="options"
        @click="deleteCoordinate(item, index)"
        @open="handlerOpen(index)"
      >
        <!-- <coordinate-item :coordinate="item"></coordinate-item> -->
        <view class="list-lay">
          <view class="list-lay__item">
            坐标名称：{{ item.pointName || '' }}
          </view>
          <view class="list-lay__item" v-if="item.positionType">
            位置类型：出入口
          </view>
          <view class="list-lay__item" v-if="item.pointCoordinatesJson && item.pointCoordinatesJson.coordinates">
            坐标：{{ item.pointCoordinatesJson.coordinates[0] || '' }},{{ item.pointCoordinatesJson.coordinates[1] || '' }}
          </view>
          <view class="list-lay__item" v-else>
            坐标：
          </view>
        </view>
      </u-swipe-action>
    </view>
    </view>
    <view class="space-content"></view>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls">
      <u-button class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit()">
        提交
      </u-button>
    </view>
    <u-popup
      :mask-close-able="false"
      v-model="pointPopupShow"
      border-radius="20"
      mode="center"
      width="80%"
      height="630rpx"
    >
      <view class="point-popup-lay">
        <view class="point-popup-lay__title"> 位置信息 </view>
        <view style="margin: 32rpx 0">
          <u-form :model="pointForm" style="padding: 0px 10px;" ref="pointForm" :error-type="errorType">
            <u-form-item label="坐标名称" prop="pointName" :label-width="130">
              <u-input
                input-align="right"
                :custom-style="valueStyle"
                placeholder="请输入坐标名称"
                v-model="pointForm.pointName"
              />
            </u-form-item>
            <u-form-item label="位置类型" prop="positionTypeName" :label-width="130">
              <u-input input-align="right" :disabled="true" v-model="pointForm.positionTypeName" type="select" placeholder="请选择" @click="positionTypeClick"/>
              <u-select v-model="positionTypeShow" mode="single-column" :list="positionTypeList" @confirm="positionTypeConfirm"></u-select>
            </u-form-item>
            <u-form-item label="坐标" prop="coordinates" :label-width="130">
              <u-input placeholder="请选择" :disabled="true" input-align="right" v-model="pointForm.coordinates"></u-input>
              <u-icon
                name="map-fill" :color="$theme.u_type_primary" size="50"
                @click="getLocation('point')"
              ></u-icon>
            </u-form-item>
          </u-form>
        </view>
        <view class="point-popup-lay__btns">
          <u-button
            plain
            type="primary"
            size="medium"
            @click="
              () => {
                pointPopupShow = false;
              }
            "
          >
            取&nbsp;&nbsp;&nbsp;&nbsp;消
          </u-button>
          <u-button type="primary" size="medium" @click="savePointPopup">
            保&nbsp;&nbsp;&nbsp;&nbsp;存
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script>
  import { uuid } from '@/common/util.js'
  import MescrollMoreMixin from "@/components/mescroll-uni/mixins/mescroll-more.js";
  import CoordinateItem from './components/CoordinateItem'
  import queryService from '@/service/query/query.service.js';
  export default {
    mixins: [ MescrollMoreMixin ],
    components: { CoordinateItem },
    data () {
      return {
        searchKey: "",
        just: '',
        title:'添加中小学',
        submitBtnLoading: false,
        errorType: ["border-bottom","message",],
        valueStyle: {
          marginRight: "5px",
        },
        schoolForm: {
          prohibitUuid: null,
          prohibitName: '',
          prohibitClassifyCode: '',
          prohibitClassifyName: '',
          prohibitAddr: '',
          ownOrgUuid: ''
        },
        rules: {
          prohibitName: [
            {
              required: true,
              message: '请输入区域名称',
              trigger: ['change','blur',],
            }
          ],
          prohibitClassifyName: [
            {
              required: true,
              message: '请选择区域类型',
              trigger: ['change','blur',],
            }
          ],
          prohibitAddr: [
            {
              required: true,
              message: '请输入地址',
              trigger: ['change','blur',],
            }
          ]
        },
        prohibitClassifyShow: false,
        prohibitClassifyList: [
          { value: '0101', label: '幼儿园' },
          { value: '0102', label: '中小学' }
        ],
        coordinatesList: [], // 添加的位置信息集合
        options: [
          {
            text: '删除',
            style: {
              backgroundColor: '#dd524d',
            },
          },
        ],
        pointPopupShow: false,
        pointForm: {
          positionUuid: '',
          prohibitUuid: '',
          pointName: '',
          positionType: '3',
          positionTypeName: '出入口',
          pointCoordinatesJson: null,
          coordinates: ''
        },
        positionTypeShow: false,
        positionTypeList: [
          // { value: '1', label: '中心点' },
          { value: '3', label: '出入口' }
        ],
        handlerType: 'add',
        userInfo: null,
        locationType: 'point'
      }
    },
    onReady() {
      this.$refs.uForm && this.$refs.uForm.setRules(this.rules);
    },
    onLoad(opt){
      let userData = uni.getStorageSync("user")
      this.userInfo = JSON.parse(userData);
      this.handlerType = opt.type
      if (opt.type === 'edit'){
        this.getProhibitDetail(opt.prohibitUuid)
      } else {
        this.schoolForm.ownOrgUuid = this.userInfo.orgUuid
      }
    },
    mounted () {

    },
    methods: {
      // 获取区域信息及位置信息详情
      getProhibitDetail (id) {
        this.$u.loading('正在加载...');
        queryService.prohibitInfo({prohibitUuid: id}).then(res => {
          this.$u.hideLoading();
          if (res.success) {
            this.schoolForm = res.bean
            if (this.schoolForm.prohibitClassifyCode === '0101') {
              this.schoolForm.prohibitClassifyName = '幼儿园'
            } else {
              this.schoolForm.prohibitClassifyName = '中小学'
            }
            if (res.bean.prohibitPositionsList) {
              this.coordinatesList = res.bean.prohibitPositionsList
              this.coordinatesList = this.coordinatesList.map(v=>{
                v.pointCoordinatesJson = JSON.parse(v.pointCoordinatesJson)
                return v
              })
              console.log(this.coordinatesList)
            }
          }
        }).catch(err => {
          this.$u.hideLoading();
          this.$u.toast(err);
        })
      },
      // 区域类型
      prohibitClassifyClick() {
        this.prohibitClassifyShow = true
      },
      prohibitClassifyConfirm(e) {
        this.schoolForm.prohibitClassifyCode = e[0].value
        this.schoolForm.prohibitClassifyName = e[0].label
      },
      // 添加位置信息
      handlerDoMore() {
        this.pointPopupShow = true
        this.pointForm = {
          // positionUuid: uuid(),
          prohibitUuid: this.schoolForm.prohibitUuid,
          pointName: '',
          positionType: '3',
          positionTypeName: '出入口',
          pointCoordinatesJson: null,
          coordinates: ''
        }
      },
      // 删除坐标
      deleteCoordinate(cItem, index) {
        if (cItem.positionUuid) {
          queryService.deleteProhibitPositions({positionUuid: cItem.positionUuid}).then(res => {
            if (res.success) {
              this.$u.toast("删除成功");
              this.coordinatesList.splice(index,1);
            }
          })
        } else {
          this.coordinatesList.splice(index,1);
          this.$u.toast("删除成功");
        }
        // this.coordinatesList = this.coordinatesList.filter(c => c.positionUuid != cItem.positionUuid);
      },
      handlerOpen(idx) {
        this.coordinatesList.map((c, i) => {
          c.show = i == idx;
        });
        this.$forceUpdate();
      },
      // 提交
      handlerDoSubmit() {       
          this.submitBtnLoading = true
          this.$refs.uForm.validate(valid => {
            if (valid) {
              if (this.handlerType == 'add') {
                // 学校信息保存
                queryService.saveProhibitInfo(this.schoolForm).then(res => {
                  if (res.success) {
                    this.submitBtnLoading = false
                    this.$u.route({
                      url:'pages/query/school/list',
                    });
                  }
                })
              } else {
                // 学校及位置信息保存
                let coordinates = JSON.parse(JSON.stringify(this.coordinatesList))
                coordinates.forEach(item => {
                  let pointCoordinates = {
                    "type": "Point",
                    "coordinates": [[[item.pointCoordinatesJson.coordinates[0],item.pointCoordinatesJson.coordinates[1]]]]
                  }
                  item.pointCoordinatesJson = JSON.stringify(pointCoordinates)
                });
                let params = {
                  prohibitUuid: this.schoolForm.prohibitUuid,
                  prohibitName: this.schoolForm.prohibitName,
                  prohibitClassifyCode: this.schoolForm.prohibitClassifyCode,
                  prohibitAddr: this.schoolForm.prohibitAddr,
                  prohibitPositionsList: coordinates
                }
                queryService.saveProhibitPositions(params).then(res => {
                  if (res.code == 0) {
                    this.submitBtnLoading = false
                    this.$u.route({
                      url:'pages/query/school/list',
                    });
                  } else {
                    this.submitBtnLoading = false
                  }
                })
              }              
            } else {
              this.submitBtnLoading = false
            }
          })
      },
      positionTypeClick() {
        this.positionTypeShow = true
      },
      positionTypeConfirm(e) {
        this.pointForm.positionTypeName = e[0].label
        this.pointForm.positionType = e[0].value
      },
      // 位置信息保存
      savePointPopup() {
        if (this.$u.test.isEmpty(this.pointForm.pointName))
          return this.$u.toast("坐标名称不能为空");
        if (this.$u.test.isEmpty(this.pointForm.positionType))
          return this.$u.toast("位置类型不能为空");
        if (this.$u.test.isEmpty(this.pointForm.coordinates))
          return this.$u.toast("坐标不能为空");

        let points = {
          positionUuid: this.pointForm.positionUuid,
          pointName: this.pointForm.pointName,
          positionType: this.pointForm.positionType,
          prohibitUuid: this.pointForm.prohibitUuid,
          pointCoordinatesJson: this.pointForm.pointCoordinatesJson,
          coordinates: this.pointForm.coordinates
        }
        this.coordinatesList.push(points)
        this.pointPopupShow = false
      },
      // 坐标采集
      getLocation(type) {
        // this.setRouteParam({ disable: false, step: 'start', });
        // this.$u.route('pages/commonPage/modifyLocationMap');

        this.$u.route({
          url: 'pages/query/coordinateAcquisit/infoAndPoMap', type: 'to', params: {
            retailerUuid: this.pointForm.prohibitUuid,
          }
        });
        this.locationType = type
      },
      // 获取坐标信息
      updateBackState(param) {
        if (param.params) {
          // 地址
          if ( this.locationType == 'addr' ){
            this.schoolForm.prohibitAddr = param.params.gisDesc;
            // this.$set(this.schoolForm,"prohibitAddr",param.params.gisDesc)
            this.$refs.uForm.validate();
          } else {
            // 坐标
            let lonLat = `${param.params.longitude},${param.params.latitude}`
            this.pointForm.coordinates = lonLat
            this.pointForm.pointCoordinatesJson ={
              coordinates: [param.params.longitude,param.params.latitude]
            }
          }
        }
      }
    }
  }
</script>
<style scoped lang="scss">
  .page{
    padding: 0;
  }
  .divider-info {
    font-size: 14px;
    margin: 5px 15px 10px 15px;
    color: #333;
    font-weight: 600;
    .sub-info {
      font-weight: 100;
      font-size: 14px;
      color: #000;
    }
  }
  .list-lay{
		padding: 20rpx 20rpx;
		background-color: #FFF;
    // margin: 20rpx;
    border-radius: 15px;
    &__item{
      padding:5px 3px;
    }
	}
  .point-popup-lay {
    padding: $cm-content-paddng-row;
    width: 100%;
    height: 100%;

    &__title {
      font-size: 36rpx;
      font-weight: 600;
      color: $u-main-color;
      margin: 10rpx 0;
      text-align: center;
      width: 100%;
    }

    &__btns {
      width: 100%;
      margin-top: 24rpx;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      uni-button {
        flex: 0.28;
      }
    }
  }
</style>
